<template>
	<view style="min-height: 100%;background-color: #fff;">
		<u-navbar :border-bottom="false" title="关单卫检" :title-size="36" :title-bold="true" :title-color="textColor" :background="{background:'#fff'}" >
		</u-navbar>
		<view class="bill-from-item u-p-t-35 u-p-l-35 u-p-r-35 u-p-b-20">
			<view class="u-m-b-20"><b>合同号</b>（报关合同号）</view>
			<u-input v-model="fromData.contractNo" placeholder="请输入合同号" :border="false" />
		</view>
		<view class="bill-from-item u-p-35 ">
			<view class="u-m-b-20"><b>上传文件 </b>（支持jpeg/jpg/png/bmp）</view>
			<UploadImage :fileList="fromData.resourceUrlsInit" @onSuccess="uploadDetailsChange" @onRemove="uploadDetailsChange" :maxCount="9"></UploadImage>
		</view>
		<view class=" u-p-35 ">
			<view class="u-m-b-20"><b>卫检商品明细 </b></view>
			<view class="history-container">
				<view  v-for="(item, index) in fromData.items" :key="item.id" >
					<view class="history-item u-p-t-30 u-p-b-30  u-flex ">
						<view class="iconfont icon-jianshao" style="margin-right: 20rpx;color: #FF551A;" @click="delItemBtnClick(index)" ></view>
						<image :src="item.itemResourceUrl" mode="" style="display:block;width: 100rpx;height: 100rpx;margin-right: 20rpx;border-radius: 10rpx;"></image>
						<view class="" style="flex: 1;overflow: hidden;">
							<view class="u-font-30 u-line-1" style="font-weight: 500;">{{item.itemName}}</view>
							<view class="u-flex u-row-between u-m-t-10">
								<view class="u-font-24 " v-if="item.specification" style=" display: inline-block; color: #999;background-color: #f8f8f8;padding: 10rpx 12rpx;border-radius: 10rpx;">
									{{item.specification}}
								</view>
								<view class="u-p-l-20 u-p-r-20 u-p-t-10 u-p-b-10 u-font-24" 
									style="border:1px solid #999;border-radius: 10rpx;color: #999;" 
									@click="dateShowFn(index)">
									<text></text>
								{{item.dateOfManufacture?$u.timeFormat(item.dateOfManufacture,'yyy-mm-dd'):'选择生产日期'}}
								</view>
							</view>
						</view>
					</view>
				</view>
				<view class="u-text-center u-m-t-20 u-m-b-20" v-if="fromData.items.length === 0">请添加关联商品~</view>
				<view class="u-flex u-row-center u-m-t-20" style="padding: 20rpx 0;background-color: #f8f8f8;color: #999;border-radius: 10rpx;" @click="$mRouter.push({route:'/pages/owners/billofEntryMange/addBillItem'})">
					<u-icon name="plus-circle-fill" color="#999"></u-icon>
					添加商品
				</view>
			</view>
		</view>
		<!-- 占位盒子 -->
		<view style="height: 195rpx;"></view>
		<view class="fixed-container">
			<view class="box-padding-col u-p-b-50" style="height: 140rpx;">
				<u-button shape="circle" hover-class="none" :ripple="true" :hair-line="false"
					:custom-style="getBtStyle('default', -1, 90, 28)" @click="saveOrAddBillFn">保存</u-button>
			</view>
		</view>
		<akLoading isFullScreen :active="loading"></akLoading>
		<u-calendar v-model="dateShow"  :safe-area-inset-bottom="true"	 :mode="'date'" @change="dateChangeFn"></u-calendar>
	</view>
</template>

<script>
	import UploadImage from '@/components/upload-image/index.vue';
	export default {
		components:{UploadImage },
		data() {
			return {
				dockReceiptId:'',
				fromData:{
					contractNo:'',
					resourceUrlsInit:[],
					items:[],
					resourceIds:[],
				},
				loading:false,
				dateShow:false,
				chooseDate:'',
				chooseIndex:0,
				refreshIfNeeded:false,
			}
		},
		onLoad(options) {
			if(options.type == 'edit'){
				this.dockReceiptId = options.id;
				this.getBillDetailsFn();
			}
		},
		onShow() {
			uni.$off('sendChooseItem')//建议先销毁一次监听，再进行新的一次监听，否则会出现重复监听的现象
			let that = this;
			uni.$on('sendChooseItem',function(data){
				that.fromData.items.push(...data);
			})
			// var pages = getCurrentPages(); // 获取当前页面栈
			// var currentPage = pages[pages.length - 1]; // 当前页面
			// if (currentPage._data.refreshIfNeeded) {
			// 	currentPage._data.refreshIfNeeded = false;
			// 	//这里为要调用的函数，重新获取数据，记得加上this
			// }
		},
		methods: {
			// 关单卫检图片上传
			uploadDetailsChange(val){
				this.fromData.resourceIds = val.map(item=>{
					return item.resourceId;
				});
			},
			// 保存或新增关单卫检
			async saveOrAddBillFn(){
				this.loading = true;
				if (this.fromData.contractNo =='') {
					this.loading = false;
					this.$u.toast('合同号不得为空');
					return false;
				}
				if (this.fromData.resourceIds.length === 0) {
					this.loading = false;
					this.$u.toast('单据图片不得为空');
					return false;
				}
				if (this.fromData.items.length === 0) {
					this.loading = false;
					this.$u.toast('单据关联的商品不得为空');
					return false;
				}
				let isEmptyDate = this.fromData.items.every(item => {
					return item.dateOfManufacture!=''&&item.dateOfManufacture
					})
				if (!isEmptyDate) {
					this.loading = false;
					this.$u.toast('有卫检商品的生成日期为空,请检查更改后重新提交');
					return false;
				}
				let ary =
				this.fromData.items.map(item=>{
					let obj = {
						dateOfManufacture: this.$u.timeFormat(item.dateOfManufacture,'yyyy-mm-dd'),
						itemId: item.itemId,
					}
					if(this.dockReceiptId!==''){
						id:item.id
					}
					return obj;
				});
				let params = {
					contractNo: this.fromData.contractNo,
					resourceIds: this.fromData.resourceIds,
					items:ary,
				};
				if(this.dockReceiptId === ''){
					const res  = await this.$newHttp.post('api/Product/AddDockReceipt',params);
					this.loading = false;
					if(res.code === 200){
						uni.showToast({
							icon:'success',
							title:'新增成功'
						});
						let pages = getCurrentPages(); // 当前页面
						var prevPage = pages[pages.length - 2]; //上一页页面实例
						if (typeof(prevPage) == "undefined") {
							//没上一页面
							return;
						}
						//把数据返回给上一个页面
						prevPage.$vm.Refresh(); //上一页面的刷新方法
						setTimeout(()=>
							uni.navigateBack({
								delta: 1
							})
						,1000);
					}else{
						this.$u.toast('新增失败，错误信息：'+res.erroMessage);
					}
				}else{
					params.id = this.dockReceiptId;
					const res  = await this.$newHttp.put('api/Product/ModifyDockReceipt',params);
					this.loading = false;
					if(res.code ===200){
						uni.showToast({
							icon:'success',
							title:'保存成功'
						})
					}else{
						this.$u.toast('保存失败，错误信息：'+res.erroMessage);
					}
				}
				
			},
			async getBillDetailsFn(){
				this.loading = true;
				let params = {
					dockReceiptId:this.dockReceiptId
				}
				const res = await this.$newHttp.get('api/Product/GetDockReceipt',{params:params});
				this.loading = false;
				if(res.code === 200){
					this.fromData.items = res.data.items;
					this.fromData.contractNo = res.data.contractNo;
					this.fromData.resourceUrlsInit = this.imageListInit(res.data.resourceUrls);
					this.fromData.resourceIds = res.data.resourceIds;
				}else{
					this.$u.toast('获取关单详情失败，错误信息：'+res.erroMessage)
				}
			},
			imageListInit(resource){
				let ary = [];
				resource.forEach(item=>{
					ary.push({
						id:item.id,
						url:item.url
					})
				})
				return ary;
			},
			delItemBtnClick(index){
				this.fromData.items.splice(index,1);
			},
			dateShowFn(index){
				this.chooseIndex = index;
				this.dateShow = true;
			},
			dateChangeFn(val){
				this.fromData.items[this.chooseIndex].dateOfManufacture = new Date(val.result);
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/static/iconfont/iconfont.css';
	.bill-from-item{
		border-bottom:20rpx solid #f8f8f8;
	}
	.history-container{
		// height: 600rpx;
		// overflow-y: auto;
		.history-item{
			width: 100%;
			background-color: #fff;
			border-bottom: 1px solid #eaeaea;
		}
	}
	.fixed-container{
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 195rpx;
		background-color: #fff;
		box-sizing: border-box;
		padding-top: 40rpx;
	}
	
</style>
